/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 *//*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.fb.server;

import com.fb.common.ConfigFactory;
import java.io.File;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

/**
 *
 * @author ngotandieu
 */
public class ServiceDaemon {

    private static final Logger logger = Logger.getLogger(ServiceDaemon.class);
    private static AdminWebServer adminWebServer = null;
    private static WebServer webServer = null;

    public static void main(String[] args) {
        final int backend = Integer.parseInt(ConfigFactory.getParam("rest", "app_backend"));
        final int fronend = Integer.parseInt(ConfigFactory.getParam("rest", "app_fronend"));
        
        String log4j = System.getProperty("log4j.configuration");
        if(log4j == null || log4j.isEmpty())
            PropertyConfigurator.configure("./conf/log4j.ini");
        
        try {
            if(backend == 1) {
                adminWebServer = AdminWebServer.getInstance();
                new Thread(adminWebServer).start();
            }
            
            if(fronend == 1) {
                webServer = WebServer.getInstance();
                new Thread(webServer).start();
            }
            logger.info("Server starting...");
            Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        logger.info("Shutdown thread before webserver getinstance");
                        if(adminWebServer != null)
                            adminWebServer.stop();
                        if(webServer != null)
                            webServer.stop();
                    } catch (Exception e) {}
                }
            }, "Stop Jetty Hook"));
            
        } catch (Throwable e) {
            String msg = "Exception encountered during startup.";
            logger.error(msg, e);
            System.out.println(msg);
            logger.error("Uncaught exception: " + e.getMessage());
            System.exit(3);
        }
    }
}
